package area;

import java.util.List;

public class SumOfOverlapWidth {

	List<Area> area;
	CalculatorWidth calculator = new CalculatorWidth();
	private double totalOverlapdWidths = 0;

	int primary;
	int target;

	public SumOfOverlapWidth(List<Area> area) {
		this.area = area;

		overlaps();

	}
	private void overlaps() {
		for (primary = 0; primary < area.size(); primary++) {
			for (target = primary; target < area.size(); target++) {
				if (isBottomOverlab()) {
					totalOverlapdWidths = totalOverlapdWidths + targetOverlapWidths();
				}
			}
		}
	}
	
	private boolean isBottomOverlab() {
		return area.get(primary).getCoordinate_X() < area.get(target).getCoordinate_X()
				&& area.get(target).getCoordinate_X() < primaryOverlapBottomCoordinate();
	}

	
	private double targetOverlapWidths() {
		return leftOverlap() + rightOverlap();
	}

	
	
	private double rightOverlap() {
		if ( isRightOverlap() ) {
			return calculator.width(overlapBottom(), calculateRightOverlabHeigh());
		} else {return 0;}
	}
	private double leftOverlap() {
		if (isLeftOverlap()) {
			return calculator.width(overlapBottom(), calculateLeftOverlabHeigh());			
		} else {return 0;}
	}
	
	
	private boolean isRightOverlap() {
		return area.get(primary).getCoordinate_Y() < targetOverlapHighCoordiante()
				&& targetOverlapHighCoordiante() < primaryOverlapHighCoordinate();
	}
	private boolean isLeftOverlap() {
		return area.get(primary).getCoordinate_Y() < area.get(target).getCoordinate_Y()
				&& area.get(target).getCoordinate_Y() < primaryOverlapHighCoordinate();
	}
	private double overlapBottom() {
		return  primaryOverlapBottomCoordinate() - area.get(target).getCoordinate_X();
	}
	private double calculateRightOverlabHeigh() {
		return area.get(primary).getCoordinate_Y() - targetOverlapHighCoordiante();	
	}
	private double calculateLeftOverlabHeigh() {
		return  primaryOverlapHighCoordinate() - area.get(target).getCoordinate_Y();
	}
	
	
	
	private double primaryOverlapBottomCoordinate() {
		return area.get(primary).getCoordinate_X() + area.get(primary).getWidth();
	}
	private double targetOverlapHighCoordiante() {
		return area.get(target).getCoordinate_Y() + area.get(target).getHeigh();
	}
	private double primaryOverlapHighCoordinate() {
		return area.get(primary).getCoordinate_Y() + area.get(primary).getHeigh();
	}
	
	
	
	public double getOverlapWidths() {
		return totalOverlapdWidths;
	}

}
